package com.lilosoft.core.exception;

import java.lang.reflect.UndeclaredThrowableException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.lilosoft.core.result.JsonResult;

/**
 * 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 *
 * @author qiusheng
 * @date 2018-05-30
 */
@ControllerAdvice
public class GlobalExceptionHandler {

	public Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 拦截业务异常
     */
    @ExceptionHandler(MyException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public JsonResult notFount(MyException e) {
    	logger.error("业务异常:", e);
    	
        JsonResult result = new JsonResult();
        result.setSuccess(false);
        result.setStatus(500);
        result.setMsg(e.getMessage());
        return result;
    }


    /**
     * 无权访问该资源
     */
    @ExceptionHandler(UndeclaredThrowableException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public JsonResult credentials(UndeclaredThrowableException e) {
    	logger.error("权限异常：", e);
    	
    	JsonResult result = new JsonResult();
        result.setSuccess(false);
        result.setStatus(405);
        result.setMsg("权限异常");
        return result;
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public JsonResult notFount(RuntimeException e) {
    	logger.error("服务器未知运行时异常：", e);
    	
    	JsonResult result = new JsonResult();
        result.setSuccess(false);
        result.setStatus(500);
        result.setMsg("服务器未知运行时异常");
        return result;
    }
    
    /**
     * 拦截系统异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public JsonResult notFount(Exception e) {
    	logger.error("系统异常:", e);
    	
        JsonResult result = new JsonResult();
        result.setSuccess(false);
        result.setStatus(500);
        result.setMsg("系统异常");
        return result;
    }

}
